package com.lvmama.rhino.web;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.entity.MonitorVO;
import com.lvmama.rhino.enums.CommonStringType;
import com.lvmama.rhino.pojo.OptionData;
import com.lvmama.rhino.pojo.monitor.MonitorApi;
import com.lvmama.rhino.pojo.monitor.MonitorApiFailure;
import com.lvmama.rhino.pojo.monitor.MonitorRegion;
import com.lvmama.rhino.service.MonitorApiService;
import com.lvmama.rhino.service.MonitorFailureApiService;
import com.lvmama.rhino.service.MonitorRegionService;
import com.lvmama.rhino.utils.DateUtil;

@Controller
@RequestMapping("performanceStatistics")
public class PerformanceStatisticsController extends BaseControllerSupport{
	
	@Autowired
	private MonitorApiService monitorApiService;
	
	@Autowired
	private MonitorRegionService monitorRegionService;
	
    @Autowired
    private MonitorFailureApiService monitorFailureApiService;
    
    /**
     * 单个接口性能
     * @param model
     * @return
     */
    @RequestMapping("interfacePerformanceMonitoring")
    public String interfacePerformanceMonitoring(ModelMap model,MonitorVO monitorVO){
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        String chooseTimeTableVO = monitorVO.getChooseTimeTableVO();
        if(chooseTimeTableVO != null && !"".equals(chooseTimeTableVO)){
            String[] split = chooseTimeTableVO.split("-");
            DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
            Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
            Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
            monitorVO.setStartDateTable(startDate);
            monitorVO.setEndDateTable(endDate);
        }
        //查询接口版本号
        String[] apiVersions = monitorApiService.queryMonitorApiVersion(monitorVO);
        //业务性能优化
        List<MonitorApi> monitorApiAvgTime = monitorApiService.querymonitorApiAvgTime(monitorVO);
        JSONArray monitorApiJsonXAxis = new JSONArray();
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        Double[] apiTimeDataList = new Double[size];
        Double[] firstPackageTimeDataList = new Double[size];
        Double[] transferTimeDataList = new Double[size];
        for(String str : dateInterval){
            monitorApiJsonXAxis.add(str);
        }
        for(int i=0;i<size;i++){
            for(MonitorApi monitorApi:monitorApiAvgTime){
                Date operDate = monitorApi.getOperDate();
                Double avgApiTime = monitorApi.getAvgApiTime();
                Double avgFirstPackageTime = monitorApi.getAvgFirstPackageTime();
                Double avgTransferTime = monitorApi.getAvgTransferTime();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                if(dateInterval[i].equals(operDateStr)){
                    apiTimeDataList[i] = avgApiTime;
                    firstPackageTimeDataList[i] = avgFirstPackageTime;
                    transferTimeDataList[i] = avgTransferTime;
                }
            }
        }
        JSONArray apiTimeJsonData = doubleArrayToJSONArray(apiTimeDataList,null);
        JSONArray firstPackageTimeJsonData = doubleArrayToJSONArray(firstPackageTimeDataList,null);
        JSONArray transferTimeJsonData = doubleArrayToJSONArray(transferTimeDataList,null);
        //接口信息
        PageInfo<MonitorApi> page = monitorApiService.queryMonitorApiDetailedList(monitorVO);
        List<MonitorApi> list = page.getList();
        for(MonitorApi monitorApi : list){
            String operators = monitorApi.getOperators();
            String networkType = monitorApi.getNetworkType();
            //根据运营商的value获得其名称
            monitorApi.setOperators(CommonStringType.getOperatorsShowNameByValue(operators));
            //根据网络类型的value获得其名称
            monitorApi.setNetworkType(CommonStringType.getNetworkTypeShowNameByValue(networkType));
        }
        model.addAttribute("page", page);
        model.addAttribute("monitorVO", monitorVO);
        model.addAttribute("apiVersions", apiVersions);
        model.addAttribute("monitorApiList", list);
        model.addAttribute("monitorApiJsonXAxis", monitorApiJsonXAxis.toJSONString());
        model.addAttribute("apiTimeJsonData", apiTimeJsonData.toJSONString());
        model.addAttribute("firstPackageTimeJsonData", firstPackageTimeJsonData.toJSONString());
        model.addAttribute("transferTimeJsonData", transferTimeJsonData.toJSONString());
        return "application/performanceStatistics/interfacePerformanceMonitoring";
    }
    
    /**
     * 根据接口名获取接口版本
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("actionApiVersion")
    @ResponseBody
    public Map<String,Object> actionApiVersion(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //查询接口版本号
        String[] apiVersions = monitorApiService.queryMonitorApiVersion(monitorVO);
        resultMap.put("apiVersions", apiVersions);
        return resultMap;
    }
    
    /**
     * 单个接口性能(业务性能服务表格数据)
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("ajaxDetailedTable")
    @ResponseBody
    public Map<String,Object> ajaxDetailedTable(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String chooseTimeTable = monitorVO.getChooseTimeTableVO();
        String chooseTimeTableVO = DateUtil.formatString(chooseTimeTable, "yyyy-MM-dd", "MM/dd/yyyy");
        monitorVO.setChooseTimeTableVO(chooseTimeTableVO+" - "+chooseTimeTableVO);
        Date startDateTable = DateUtil.parseDate(chooseTimeTable + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDateTable = DateUtil.parseDate(chooseTimeTable + " 23:59:59", "yyyy-MM-dd HH:mm:ss");;
        monitorVO.setStartDateTable(startDateTable);
        monitorVO.setEndDateTable(endDateTable);
        //接口信息
        PageInfo<MonitorApi> page = monitorApiService.queryMonitorApiDetailedList(monitorVO);
        List<MonitorApi> list = page.getList();
        for(MonitorApi monitorApi : list){
            String operators = monitorApi.getOperators();
            String networkType = monitorApi.getNetworkType();
            //根据运营商的value获得其名称
            monitorApi.setOperators(CommonStringType.getOperatorsShowNameByValue(operators));
            //根据网络类型的value获得其名称
            monitorApi.setNetworkType(CommonStringType.getNetworkTypeShowNameByValue(networkType));
        }
        resultMap.put("monitorApiList", list);
        resultMap.put("monitorVO", monitorVO);
        resultMap.put("page", page);
        return resultMap;
    }
    
    /**
     * 接口占比趋势
     * @param model
     * @return
     */
    @RequestMapping("interfaceShareTrend")
    public String interfaceShareTrend(ModelMap model, MonitorVO monitorVO) {
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        String chooseTimeTableVO = monitorVO.getChooseTimeTableVO();
        if(chooseTimeTableVO != null && !"".equals(chooseTimeTableVO)){
            String[] split = chooseTimeTableVO.split("-");
            DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
            Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
            Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
            monitorVO.setStartDateTable(startDate);
            monitorVO.setEndDateTable(endDate);
        }
        //接口占比趋势X轴数据
        JSONArray monitorAPIJsonXAxis = new JSONArray();
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        for(String str : dateInterval){
            monitorAPIJsonXAxis.add(str);
        }
        
        Double[] proportion1 = new Double[size];
        Double[] proportion2 = new Double[size];
        Double[] proportion3 = new Double[size];
        Double[] proportion4 = new Double[size];
        Double[] proportion5 = new Double[size];
        Double[] timeConsuming1 = new Double[size];
        Double[] timeConsuming2 = new Double[size];
        Double[] timeConsuming3 = new Double[size];
        Double[] timeConsuming4 = new Double[size];
        Double[] timeConsuming5 = new Double[size];
        DecimalFormat df = new DecimalFormat("#0.00");
        //接口占比趋势
        List<OptionData> options = monitorApiService.queryOptionDataList(monitorVO);
        //接口总耗时占比(首包时间+传输时间)
        List<OptionData> TimeConsumingOptions = monitorApiService.queryTimeConsumingOptionDataList(monitorVO);
        
        for(int i=0;i<size;i++){
            for(OptionData option : options){
                Date operDate = option.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                if(dateInterval[i].equals(operDateStr)){
                    Long option1 = option.getOption1();
                    Long option2 = option.getOption2();
                    Long option3 = option.getOption3();
                    Long option4 = option.getOption4();
                    Long option5 = option.getOption5();
                    Long optionSum = option.getOptionSum();
                    String str1 = df.format(((double)option1/optionSum)*100);
                    Double newData1 = Double.parseDouble(str1);
                    proportion1[i] = newData1;
                    String str2 = df.format(((double)option2/optionSum)*100);
                    Double newData2 = Double.parseDouble(str2);
                    proportion2[i] = newData2;
                    String str3 = df.format(((double)option3/optionSum)*100);
                    Double newData3 = Double.parseDouble(str3);
                    proportion3[i] = newData3;
                    String str4 = df.format(((double)option4/optionSum)*100);
                    Double newData4 = Double.parseDouble(str4);
                    proportion4[i] = newData4;
                    String str5 = df.format(((double)option5/optionSum)*100);
                    Double newData5 = Double.parseDouble(str5);
                    proportion5[i] = newData5;
                }
            }
            for(OptionData option : TimeConsumingOptions){
                Date operDate = option.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                if(dateInterval[i].equals(operDateStr)){
                    Long option1 = option.getOption1();
                    Long option2 = option.getOption2();
                    Long option3 = option.getOption3();
                    Long option4 = option.getOption4();
                    Long option5 = option.getOption5();
                    Long optionSum = option.getOptionSum();
                    String str1 = df.format(((double)option1/optionSum)*100);
                    Double newData1 = Double.parseDouble(str1);
                    timeConsuming1[i] = newData1;
                    String str2 = df.format(((double)option2/optionSum)*100);
                    Double newData2 = Double.parseDouble(str2);
                    timeConsuming2[i] = newData2;
                    String str3 = df.format(((double)option3/optionSum)*100);
                    Double newData3 = Double.parseDouble(str3);
                    timeConsuming3[i] = newData3;
                    String str4 = df.format(((double)option4/optionSum)*100);
                    Double newData4 = Double.parseDouble(str4);
                    timeConsuming4[i] = newData4;
                    String str5 = df.format(((double)option5/optionSum)*100);
                    Double newData5 = Double.parseDouble(str5);
                    timeConsuming5[i] = newData5;
                }
            }
        }
        JSONArray monitorAPIJsonProportion1 = doubleArrayToJSONArray(proportion1,null);
        JSONArray monitorAPIJsonProportion2 = doubleArrayToJSONArray(proportion2,null);
        JSONArray monitorAPIJsonProportion3 = doubleArrayToJSONArray(proportion3,null);
        JSONArray monitorAPIJsonProportion4 = doubleArrayToJSONArray(proportion4,null);
        JSONArray monitorAPIJsonProportion5 = doubleArrayToJSONArray(proportion5,null);
        
        JSONArray monitorAPIJsontimeConsuming1 = doubleArrayToJSONArray(timeConsuming1,null);
        JSONArray monitorAPIJsontimeConsuming2 = doubleArrayToJSONArray(timeConsuming2,null);
        JSONArray monitorAPIJsontimeConsuming3 = doubleArrayToJSONArray(timeConsuming3,null);
        JSONArray monitorAPIJsontimeConsuming4 = doubleArrayToJSONArray(timeConsuming4,null);
        JSONArray monitorAPIJsontimeConsuming5 = doubleArrayToJSONArray(timeConsuming5,null);
        
        Double minTime = monitorVO.getMinTime();
        if(minTime == null){
            monitorVO.setMinTime(5000.0);
            monitorVO.setMaxTime(null);
        }
        
        String timeConsumingType = monitorVO.getTimeConsumingType();
        PageInfo<MonitorApi> page = null;
        if(timeConsumingType.equals("totalTimeConsuming")){//总耗时
            //根据接口名分页查询接口搜索
            page = monitorApiService.queryMonitorApiTotalPage(monitorVO);
        }else if(timeConsumingType.equals("internalTimeConsuming")){//内部耗时
            //根据接口名分页查询接口搜索
            page = monitorApiService.queryMonitorApiPage(monitorVO);
        }
        
        int fillCount = page.getPageSize() - page.getList().size();
        model.addAttribute("page", page);
        model.addAttribute("monitorApiList", page.getList());
        model.addAttribute("fillCount", fillCount);
        model.addAttribute("monitorVO", monitorVO);
        model.addAttribute("monitorAPIJsonXAxis", monitorAPIJsonXAxis.toJSONString());
        model.addAttribute("monitorAPIJsonProportion1", monitorAPIJsonProportion1.toJSONString());
        model.addAttribute("monitorAPIJsonProportion2", monitorAPIJsonProportion2.toJSONString());
        model.addAttribute("monitorAPIJsonProportion3", monitorAPIJsonProportion3.toJSONString());
        model.addAttribute("monitorAPIJsonProportion4", monitorAPIJsonProportion4.toJSONString());
        model.addAttribute("monitorAPIJsonProportion5", monitorAPIJsonProportion5.toJSONString());
        model.addAttribute("monitorAPIJsontimeConsuming1", monitorAPIJsontimeConsuming1.toJSONString());
        model.addAttribute("monitorAPIJsontimeConsuming2", monitorAPIJsontimeConsuming2.toJSONString());
        model.addAttribute("monitorAPIJsontimeConsuming3", monitorAPIJsontimeConsuming3.toJSONString());
        model.addAttribute("monitorAPIJsontimeConsuming4", monitorAPIJsontimeConsuming4.toJSONString());
        model.addAttribute("monitorAPIJsontimeConsuming5", monitorAPIJsontimeConsuming5.toJSONString());
        return "application/performanceStatistics/interfaceShareTrend";
    }
    
    /**
     * 多维度查询曲线
     * @param model
     * @return
     */
	@RequestMapping("multidimensionalQueryCurve")
    public String multidimensionalQueryCurve(ModelMap model, MonitorVO monitorVO) {
        monitorVO = queryPageMonitorVO(monitorVO);//获取页面上的查询条件
	    model.addAttribute("monitorVO", monitorVO);
    	return "application/performanceStatistics/multidimensionalQueryCurve";
    }
    
    
    /**
     * 多维度查询曲线AJAX请求
     * @param model
     * @return
     * @throws ParseException 
     */
	@RequestMapping("ajaxmultidimensionalQueryCurve")
    @ResponseBody
    public Map<String, Object> ajaxmultidimensionalQueryCurve(MonitorVO monitorVO) throws ParseException {
	    Map<String, Object> resultMap = new HashMap<String, Object>();
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        //所有接口不同网络、不同地区和运营商调用耗时X轴数据
        JSONArray monitorAPIJsonXAxis = new JSONArray();
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        for(String str : dateInterval){
            monitorAPIJsonXAxis.add(str);
        }
        
        //所有接口运营商调用耗时
        List<MonitorApi> monitorApiOperatorsList = monitorApiService.queryMonitorApiOperatorsList(monitorVO);
        //所有接口运营商调用耗时Y轴数据
        Double[] cuData = new Double[size];
        Double[] ctData = new Double[size];
        Double[] cmData = new Double[size];
        Double[] noneData = new Double[size];
       /* for(int i = 0; i < size; i++){
            cuData[i] = 0.0;
            ctData[i] = 0.0;
            cmData[i] = 0.0;
            noneData[i] = 0.0;
        }*/
        for(int i=0;i<size;i++){
            for(MonitorApi monitorApi : monitorApiOperatorsList){
                Date operDate = monitorApi.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                String operators = monitorApi.getOperators();
                Double avgApiTime = monitorApi.getAvgApiTime();
                if(operDate != null && operators != null){
                    if(operators.equals(CommonStringType.CM.getValue()) && dateInterval[i].equals(operDateStr)){
                        cmData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.CU.getValue()) && dateInterval[i].equals(operDateStr)){
                        cuData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.CT.getValue()) && dateInterval[i].equals(operDateStr)){
                        ctData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.NONE1.getValue()) && dateInterval[i].equals(operDateStr)){
                        noneData[i] = avgApiTime;
                    }
                }
            }
        }
        resultMap.put("dateInterval", dateInterval);
        resultMap.put("cuData", cuData);
        resultMap.put("ctData", ctData);
        resultMap.put("cmData", cmData);
        resultMap.put("noneData", noneData);
        
      //所有接口不同网络制式调用耗时
        List<MonitorApi> monitorApiNetworkTypeList = monitorApiService.queryMonitorApiNetworkTypeList(monitorVO);
        //所有接口不同网络制式调用耗时Y轴数据
        Double[] twoGData = new Double[size];
        Double[] threeGData = new Double[size];
        Double[] fourGData = new Double[size];
        Double[] wifiData = new Double[size];
        Double[] noneNetData = new Double[size];
        /*for(int i = 0; i < size; i++){
            twoGData[i] = 0.0;
            threeGData[i] = 0.0;
            fourGData[i] = 0.0;
            wifiData[i] = 0.0;
            noneNetData[i] = 0.0;
        }*/
        for(int i=0;i<size;i++){
            for(MonitorApi monitorApi : monitorApiNetworkTypeList){
                Date operDate = monitorApi.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                String networkType = monitorApi.getNetworkType();
                Double avgApiTime = monitorApi.getAvgApiTime();
                if(operDate != null && networkType != null){
                    if(networkType.equals(CommonStringType.TWO_G.getValue()) && dateInterval[i].equals(operDateStr)){
                        twoGData[i] = avgApiTime;
                    }else if(networkType.equals(CommonStringType.THREE_G.getValue()) && dateInterval[i].equals(operDateStr)){
                        threeGData[i] = avgApiTime;
                    }else if(networkType.equals(CommonStringType.FOUR_G.getValue()) && dateInterval[i].equals(operDateStr)){
                        fourGData[i] = avgApiTime;
                    }else if(networkType.equals(CommonStringType.WIFI.getValue()) && dateInterval[i].equals(operDateStr)){
                        wifiData[i] = avgApiTime;
                    }else if(networkType.equals(CommonStringType.NONE2.getValue()) && dateInterval[i].equals(operDateStr)){
                        noneNetData[i] = avgApiTime;
                    }
                }
            }
        }
        resultMap.put("twoGData", twoGData);
        resultMap.put("threeGData", threeGData);
        resultMap.put("fourGData", fourGData);
        resultMap.put("wifiData", wifiData);
        resultMap.put("noneNetData", noneNetData);
        
      //所有接口不同地区调用耗时
        List<MonitorRegion> monitorRegionProvinces = monitorRegionService.queryMonitorRegionProvince(monitorVO);
        int regionCount = monitorRegionProvinces.size();
        String[] monitorRegionProvince = new String[regionCount];
        for(int i = 0;i< regionCount;i++){
            monitorRegionProvince[i] = monitorRegionProvinces.get(i).getProvince();
        }
        //查询不同地区的接口信息
        List<MonitorRegion> monitorRegionVersionList = monitorRegionService.queryMonitorRegionProvinceList(monitorVO);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for(int j=0;j< monitorRegionProvince.length;j++){
            Map<String, Object> map = new HashMap<String, Object>();
            Double[] arr = new Double[size];
            /*for(int i = 0; i < size; i++){
                arr[i] = 0.0;
            }*/
            for(int i=0;i<size;i++){
                for(MonitorRegion monitorRegion : monitorRegionVersionList){
                    Date operDate = monitorRegion.getOperDate();
                    String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                    String province = monitorRegion.getProvince();
                    Double avgApiTime = monitorRegion.getAvgApiTime();
                    if(dateInterval[i].equals(operDateStr) && monitorRegionProvince[j].equals(province)){
                        arr[i]=avgApiTime;
                    }
                }
            }
            map.put("name", monitorRegionProvince[j]);
            map.put("type", "line");
            map.put("data", arr);
            list.add(map);
        }
        resultMap.put("legend", monitorRegionProvince);
        resultMap.put("series", list);
        return resultMap;
    }
	
    
    /**
     * 所有接口错误率
     * @param model
     * @return
     */
    @RequestMapping("allInterfaceErrorRates")
    public String allInterfaceErrorRates(ModelMap model,MonitorVO monitorVO) {
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        String chooseTimeTableVO = monitorVO.getChooseTimeTableVO();
        if(chooseTimeTableVO != null && !"".equals(chooseTimeTableVO)){
            String[] split = chooseTimeTableVO.split("-");
            DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
            Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
            Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
            monitorVO.setStartDateTable(startDate);
            monitorVO.setEndDateTable(endDate);
        }
        //接口占比趋势X轴数据
        JSONArray monitorFailuerAPIJsonXAxis = new JSONArray();
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        for(String str : dateInterval){
            monitorFailuerAPIJsonXAxis.add(str);
        }
        
        Double[] proportion1 = new Double[size];
        Double[] proportion2 = new Double[size];
        DecimalFormat df = new DecimalFormat("#0.00000");
        //根据网络类型的value获得其名称
        List<MonitorApi> amountSumList = monitorApiService.queryAmountSum(monitorVO);
        List<OptionData> options = monitorFailureApiService.queryOptionDataList(monitorVO);
        for(int i=0;i<size;i++){
            for(OptionData option : options){
                Date operDate = option.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                for(MonitorApi monitorApi : amountSumList){
                    Date monitorApiOperDate = monitorApi.getOperDate();
                    String monitorApiOperDateStr = DateUtil.dateFormat(monitorApiOperDate, "yyyy-MM-dd");
                    if(dateInterval[i].equals(operDateStr) && dateInterval[i].equals(monitorApiOperDateStr)){
                        Long option1 = option.getOption1();
                        Long option2 = option.getOption2();
                        Long optionSum = option.getOptionSum()+monitorApi.getAmount();
                        String str1 = df.format(((double)option1/optionSum)*100);
                        Double newData1 = Double.parseDouble(str1);
                        proportion1[i] = newData1;
                        String str2 = df.format(((double)option2/optionSum)*100);
                        Double newData2 = Double.parseDouble(str2);
                        proportion2[i] = newData2;
                    }
                }
            }
        }
        JSONArray monitorFailuerAPIJsonProportion1 = doubleArrayToJSONArray(proportion1,null);
        JSONArray monitorFailuerAPIJsonProportion2 = doubleArrayToJSONArray(proportion2,null);
        
        //分页查询失败接口信息
        PageInfo<MonitorApiFailure> page = monitorFailureApiService.queryMonitorFailureApiPage(monitorVO);
        List<MonitorApiFailure> list = page.getList();
        for(MonitorApiFailure monitorApiFailure : list){
            String method = monitorApiFailure.getMethod();
            String failuerType = monitorApiFailure.getFailuerType();
            String failureCode = monitorApiFailure.getFailureCode();
            //分页查询失败接口信息
            monitorApiFailure.setMethod(CommonStringType.getMethodShowNameByValue(method));
            //分页查询失败接口信息
            monitorApiFailure.setFailuerType(CommonStringType.getExceptionShowNameByValue(failuerType));
            if("1".equals(failuerType)){
                //根据接口异常的value获得其名称
                monitorApiFailure.setFailureCode(CommonStringType.getInterfaceExceptionShowNameByValue(failureCode));
            }
        }
        
        model.addAttribute("page", page);
        model.addAttribute("monitorFailureApiList", list);
        model.addAttribute("monitorVO", monitorVO);
        model.addAttribute("monitorFailuerAPIJsonXAxis", monitorFailuerAPIJsonXAxis.toJSONString());
        model.addAttribute("monitorFailuerAPIJsonProportion1", monitorFailuerAPIJsonProportion1.toJSONString());
        model.addAttribute("monitorFailuerAPIJsonProportion2", monitorFailuerAPIJsonProportion2.toJSONString());
        return "application/performanceStatistics/allInterfaceErrorRates";
    }
    
    /**
     * 全国接口性能
     * @param model
     * @return
     */
    @RequestMapping("nationalInterfacePerformance")
    public String nationalInterfacePerformance(ModelMap model, MonitorVO monitorVO){
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        String searchType = monitorVO.getSearchType();
        //根据条件查询各地区监控信息
        List<MonitorRegion> monitorRegionList = monitorRegionService.queryMonitorRegions(monitorVO);
        PageInfo<MonitorRegion> page = monitorRegionService.queryMonitorRegionsPage(monitorVO);
        JSONArray monitorRegionJson = new JSONArray();
        if(searchType.equals("avg_api_time")){
            for (MonitorRegion monitorRegion : monitorRegionList) {
                JSONObject node = new JSONObject();
                node.put("name", monitorRegion.getProvince());
                node.put("value", monitorRegion.getAvgApiTime());
                monitorRegionJson.add(node);
            }
        }else if(searchType.equals("amount")){
            for (MonitorRegion monitorRegion : monitorRegionList) {
                JSONObject node = new JSONObject();
                node.put("name", monitorRegion.getProvince());
                node.put("value", monitorRegion.getAmount());
                monitorRegionJson.add(node);
            }
        }
        
        if(searchType.equals("avg_api_time")){
            //全国运营商性能对比X轴数据
            JSONArray monitorRegionJsonXAxis = new JSONArray();
            String[] dateInterval = monitorVO.getDateInterval();
            int size = dateInterval.length;
            for(String str : dateInterval){
                monitorRegionJsonXAxis.add(str);
            }
            
            //全国运营商性能对比各运营商Y轴数据
            Double[] avgData = new Double[size];
            Double[] cuData = new Double[size];
            Double[] ctData = new Double[size];
            Double[] cmData = new Double[size];
            Double[] noneData = new Double[size];
            //全国运营商性能对比折线图
            List<MonitorRegion> monitorRegionListline = monitorRegionService.queryMonitorRegionsline(monitorVO);
            //全国运营商性能对比折线图(平均耗时)
            List<MonitorRegion> monitorRegionListlineAvg = monitorRegionService.queryMonitorRegionslineAvg(monitorVO);
            for(int i=0;i<size;i++){
                for(MonitorRegion monitorRegion : monitorRegionListline){
                    Date operDate = monitorRegion.getOperDate();
                    String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                    String operators = monitorRegion.getOperators();
                    Double avgApiTime = monitorRegion.getAvgApiTime();
                    if(operDate != null && operators != null){
                        if(operators.equals(CommonStringType.CM.getValue()) && dateInterval[i].equals(operDateStr)){
                            cmData[i] = avgApiTime;
                        }else if(operators.equals(CommonStringType.CU.getValue()) && dateInterval[i].equals(operDateStr)){
                            cuData[i] = avgApiTime;
                        }else if(operators.equals(CommonStringType.CT.getValue()) && dateInterval[i].equals(operDateStr)){
                            ctData[i] = avgApiTime;
                        }else if(operators.equals(CommonStringType.NONE1.getValue()) && dateInterval[i].equals(operDateStr)){
                            noneData[i] = avgApiTime;
                        }
                    }
                }
                for(MonitorRegion monitorRegion : monitorRegionListlineAvg){
                    Date operDate = monitorRegion.getOperDate();
                    String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                    String operators = monitorRegion.getOperators();
                    Double avgApiTime = monitorRegion.getAvgApiTime();
                    if(operDate != null && operators != null){
                        if(dateInterval[i].equals(operDateStr)){
                            avgData[i] = avgApiTime;
                        }
                    }
                }
            }
        
          //运营商首包时间和下载时长对比
            Double[] avgFirstPackageTimeData = new Double[5];
            Double[] transferTimeData = new Double[5];
            Double avgFirstPackageTimeDataSum = 0.0;
            Double transferTimeSum = 0.0;
            Integer countSum = 0;
            //全国运营商首包时间和下载时长对比
            List<MonitorRegion> monitorRegionListBar = monitorRegionService.queryMonitorRegionsBar(monitorVO);
            for(MonitorRegion monitorRegion : monitorRegionListBar){
                String operators = monitorRegion.getOperators();
                Double avgFirstPackageTime = monitorRegion.getAvgFirstPackageTime();
                Double transferTime = monitorRegion.getTransferTime();
                Integer count =monitorRegion.getCount();
                avgFirstPackageTimeDataSum += avgFirstPackageTime*count;
                transferTimeSum += transferTime*count;
                countSum += count;
                if(operators.equals(CommonStringType.CM.getValue())){
                    avgFirstPackageTimeData[1] = avgFirstPackageTime;
                    transferTimeData[1] = transferTime;
                }else if(operators.equals(CommonStringType.CT.getValue())){
                    avgFirstPackageTimeData[2] = avgFirstPackageTime;
                    transferTimeData[2] = transferTime;
                }else if(operators.equals(CommonStringType.CU.getValue())){
                    avgFirstPackageTimeData[3] = avgFirstPackageTime;
                    transferTimeData[3] = transferTime;
                }else if(operators.equals(CommonStringType.NONE1.getValue())){
                    avgFirstPackageTimeData[4] = avgFirstPackageTime;
                    transferTimeData[4] = transferTime;
                }
            }
            if(countSum != 0){
                avgFirstPackageTimeData[0] = avgFirstPackageTimeDataSum/countSum;
                transferTimeData[0] = transferTimeSum/countSum;
            }
            
            //数据格式转换为json
            DecimalFormat df = new DecimalFormat("#0.00");
            JSONArray monitorRegionJsonCMData = doubleArrayToJSONArray(cmData,df);
            JSONArray monitorRegionJsonCUData = doubleArrayToJSONArray(cuData,df);
            JSONArray monitorRegionJsonCTData = doubleArrayToJSONArray(ctData,df);
            JSONArray monitorRegionJsonNONEData = doubleArrayToJSONArray(noneData,df);
            JSONArray monitorRegionJsonAvgData = doubleArrayToJSONArray(avgData,df);
            JSONArray avgFirstPackageTimeDataJson = doubleArrayToJSONArray(avgFirstPackageTimeData,df);
            JSONArray transferTimeDataJson = doubleArrayToJSONArray(transferTimeData,df);
            
            model.addAttribute("monitorRegionJsonXAxis", monitorRegionJsonXAxis.toJSONString());
            model.addAttribute("monitorRegionJsonCMData", monitorRegionJsonCMData.toJSONString());
            model.addAttribute("monitorRegionJsonCUData", monitorRegionJsonCUData.toJSONString());
            model.addAttribute("monitorRegionJsonCTData", monitorRegionJsonCTData.toJSONString());
            model.addAttribute("monitorRegionJsonNONEData", monitorRegionJsonNONEData.toJSONString());
            model.addAttribute("monitorRegionJsonAvgData", monitorRegionJsonAvgData.toJSONString());
            model.addAttribute("avgFirstPackageTimeDataJson", avgFirstPackageTimeDataJson.toJSONString());
            model.addAttribute("transferTimeDataJson", transferTimeDataJson.toJSONString());
        }
        
        model.addAttribute("page", page);
        model.addAttribute("monitorRegionList", page.getList());
        model.addAttribute("monitorVO", monitorVO);
        model.addAttribute("monitorRegionJson", monitorRegionJson.toJSONString());
        MonitorRegion monitorRegionMax = monitorRegionService.queryMonitorRegionsMax(monitorVO);
        if(monitorRegionMax != null){
            model.addAttribute("monitorRegionMax", monitorRegionMax);
        }
        return "application/performanceStatistics/nationalInterfacePerformance";
    }  
    
    /**
     * 将Double类型的数组转换为JSONArray
     * @param array
     * @param df
     * @return
     */
    public JSONArray doubleArrayToJSONArray (Double[] array,DecimalFormat df){
        JSONArray jSONArray = new JSONArray();
        for(Double data : array){
           /* if(data == null){
                data = 0.00;
            }*/
            if(df != null && data != null){
                String str = df.format(data.doubleValue());
                data = Double.parseDouble(str);
            }
            jSONArray.add(data);
        }
        return jSONArray;
    }
    
    
    /**
     * 接口搜索
     * @param model
     * @return
     */
    @RequestMapping("interfaceSearch")
    public String interfaceSearch(ModelMap model,MonitorVO monitorVO){
        monitorVO = queryMonitorVO(monitorVO);
        //根据接口名分页查询接口搜索
        PageInfo<MonitorApi> page = monitorApiService.queryMonitorApiSearchPage(monitorVO);
        List<MonitorApi> list = page.getList();
        DecimalFormat df = new DecimalFormat("#0.00");
        for(MonitorApi monitorApi : list){
            Long apiFailAmount=  monitorApi.getApiFailAmount()==null?0:monitorApi.getApiFailAmount();
            Long amount = monitorApi.getAmount();
            String successRate = df.format(((double)(amount-apiFailAmount)/amount)*100)+"%";
            monitorApi.setSuccessRate(successRate);
        }
        model.addAttribute("monitorVO", monitorVO);
        model.addAttribute("page", page);
        model.addAttribute("monitorApiList", list);
        return "application/performanceStatistics/interfaceSearch";
    }
    
    /**
     * 全国接口性能地图的点击事件
     * @param monitorVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("ajaxLineAndBar")
    @ResponseBody
    public Map<String,Object> data(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response)
        throws Exception{
        /*response.setContentType("text/html;charset=utf-8");
        String province=request.getParameter("province");*/
        monitorVO = queryMonitorVO(monitorVO);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //全国运营商性能对比X轴数据
          JSONArray monitorRegionJsonXAxis = new JSONArray();
          String[] dateInterval = monitorVO.getDateInterval();
          int size = dateInterval.length;
          for(String str : dateInterval){
              monitorRegionJsonXAxis.add(str);
          }
          
          //全国运营商性能对比各运营商Y轴数据
          Double[] avgData = new Double[size];
          Double[] cuData = new Double[size];
          Double[] ctData = new Double[size];
          Double[] cmData = new Double[size];
          Double[] noneData = new Double[size];
          //全国运营商性能对比折线图
          List<MonitorRegion> monitorRegionListline = monitorRegionService.queryMonitorRegionsline(monitorVO);
          //全国运营商性能对比折线图(平均耗时)
          List<MonitorRegion> monitorRegionListlineAvg = monitorRegionService.queryMonitorRegionslineAvg(monitorVO);
          for(int i=0;i<size;i++){
              for(MonitorRegion monitorRegion : monitorRegionListline){
                  Date operDate = monitorRegion.getOperDate();
                  String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                  String operators = monitorRegion.getOperators();
                  Double avgApiTime = monitorRegion.getAvgApiTime();
                  if(operDate != null && operators != null){
                      if(operators.equals(CommonStringType.CM.getValue()) && dateInterval[i].equals(operDateStr)){
                          cmData[i] = avgApiTime;
                      }else if(operators.equals(CommonStringType.CU.getValue()) && dateInterval[i].equals(operDateStr)){
                          cuData[i] = avgApiTime;
                      }else if(operators.equals(CommonStringType.CT.getValue()) && dateInterval[i].equals(operDateStr)){
                          ctData[i] = avgApiTime;
                      }else if(operators.equals(CommonStringType.NONE1.getValue()) && dateInterval[i].equals(operDateStr)){
                          noneData[i] = avgApiTime;
                      }
                  }
              }
              for(MonitorRegion monitorRegion : monitorRegionListlineAvg){
                  Date operDate = monitorRegion.getOperDate();
                  String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                  String operators = monitorRegion.getOperators();
                  Double avgApiTime = monitorRegion.getAvgApiTime();
                  if(operDate != null && operators != null){
                      if(dateInterval[i].equals(operDateStr)){
                          avgData[i] = avgApiTime;
                      }
                  }
              }
          }
          
          Double[] avgFirstPackageTimeData = new Double[5];
          Double[] transferTimeData = new Double[5];
          Double avgFirstPackageTimeDataSum = 0.0;
          Double transferTimeSum = 0.0;
          Integer countSum = 0;
          //全国运营商首包时间和下载时长对比
          List<MonitorRegion> monitorRegionListBar = monitorRegionService.queryMonitorRegionsBar(monitorVO);
          for(MonitorRegion monitorRegion : monitorRegionListBar){
              String operators = monitorRegion.getOperators();
              Double avgFirstPackageTime = monitorRegion.getAvgFirstPackageTime();
              Double transferTime = monitorRegion.getTransferTime();
              Integer count =monitorRegion.getCount();
              avgFirstPackageTimeDataSum += avgFirstPackageTime*count;
              transferTimeSum += transferTime*count;
              countSum += count;
              if(operators.equals(CommonStringType.CM.getValue())){
                  avgFirstPackageTimeData[1] = avgFirstPackageTime;
                  transferTimeData[1] = transferTime;
              }else if(operators.equals(CommonStringType.CT.getValue())){
                  avgFirstPackageTimeData[2] = avgFirstPackageTime;
                  transferTimeData[2] = transferTime;
              }else if(operators.equals(CommonStringType.CU.getValue())){
                  avgFirstPackageTimeData[3] = avgFirstPackageTime;
                  transferTimeData[3] = transferTime;
              }else if(operators.equals(CommonStringType.NONE1.getValue())){
                  avgFirstPackageTimeData[4] = avgFirstPackageTime;
                  transferTimeData[4] = transferTime;
              }
          }
          avgFirstPackageTimeData[0] = avgFirstPackageTimeDataSum/countSum;
          transferTimeData[0] = transferTimeSum/countSum;
          
          //数据格式转换为json
          DecimalFormat df = new DecimalFormat("#0.00");
          cmData = arrayToDecimalFormat(cmData,df);
          cuData = arrayToDecimalFormat(cuData,df);
          ctData = arrayToDecimalFormat(ctData,df);
          noneData = arrayToDecimalFormat(noneData,df);
          avgData = arrayToDecimalFormat(avgData,df);
          avgFirstPackageTimeData = arrayToDecimalFormat(avgFirstPackageTimeData,df);
          transferTimeData = arrayToDecimalFormat(transferTimeData,df);
          
          resultMap.put("dateInterval", dateInterval);
          resultMap.put("cmData", cmData);
          resultMap.put("cuData", cuData);
          resultMap.put("ctData", ctData);
          resultMap.put("noneData", noneData);
          resultMap.put("avgData", avgData);
          resultMap.put("avgFirstPackageTimeData", avgFirstPackageTimeData);
          resultMap.put("transferTimeData", transferTimeData);
          return resultMap;
    }
    
    /**
     * Double数组遍历按df格式修改
     * @param array
     * @param df
     * @return
     */
    public Double[] arrayToDecimalFormat(Double[] array,DecimalFormat df){
        for(int i = 0; i< array.length;i++){
            if(array[i] == null){
                array[i] = 0.00;
            }
            String str = df.format(array[i].doubleValue());
            array[i] = Double.parseDouble(str);
        }
        return array;
    }
    
    
    public MonitorVO queryMonitorVO(MonitorVO monitorVO){
        if(monitorVO.getSearchType() == null){
            monitorVO.setSearchType("avg_api_time");
        }
        if(monitorVO.getTimeConsumingType() == null){
            monitorVO.setTimeConsumingType("internalTimeConsuming");
        }
        if(monitorVO.getChooseTimeVO() == null){
            Date date = new Date();
            String startDateStr = DateUtil.getStrDayOfMonth(date, -7, "MM/dd/yyyy");
            String endDateStr = DateUtil.getStrDayOfMonth(date, -1, "MM/dd/yyyy");
            monitorVO.setChooseTimeVO(startDateStr + " - " + endDateStr);
        }
      //切割字符串，获取开启时间和结束时间
        String[] split = monitorVO.getChooseTimeVO().split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
        Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
        monitorVO.setStartDate(startDate);
        monitorVO.setEndDate(endDate);
        //获取区间内日期
        String[] strDate = DateUtil.getBetweenTime(startDate, endDate, "yyyy-MM-dd");
        monitorVO.setDateInterval(strDate);
        return monitorVO;
    }
    
    
    /**
     * 接口占比趋势点击事件
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("ajaxTable")
    @ResponseBody
    public Map<String,Object> ajaxTable(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String chooseTime = monitorVO.getChooseTimeVO();
        String chooseTimeVO = DateUtil.formatString(chooseTime, "yyyy-MM-dd", "MM/dd/yyyy");
        monitorVO.setChooseTimeTableVO(chooseTimeVO+" - "+chooseTimeVO);
        Date startDate = DateUtil.parseDate(chooseTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtil.parseDate(chooseTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        monitorVO.setStartDateTable(startDate);
        monitorVO.setEndDateTable(endDate);
        String seriesIndex = monitorVO.getSeriesIndex();
        if(seriesIndex.equals("0")){
            monitorVO.setMinTime(0.0);
            monitorVO.setMaxTime(1000.0);
        }else if(seriesIndex.equals("1")){
            monitorVO.setMinTime(1000.0);
            monitorVO.setMaxTime(2000.0);
        }else if(seriesIndex.equals("2")){
            monitorVO.setMinTime(2000.0);
            monitorVO.setMaxTime(3000.0);
        }else if(seriesIndex.equals("3")){
            monitorVO.setMinTime(3000.0);
            monitorVO.setMaxTime(5000.0);
        }else if(seriesIndex.equals("4")){
            monitorVO.setMinTime(5000.0);
            monitorVO.setMaxTime(null);
        }
        String timeConsumingType = monitorVO.getTimeConsumingType();
        PageInfo<MonitorApi> page = null;
        if(timeConsumingType.equals("totalTimeConsuming")){//总耗时
            //根据接口名分页查询接口搜索
            page = monitorApiService.queryMonitorApiTotalPage(monitorVO);
        }else if(timeConsumingType.equals("internalTimeConsuming")){//内部耗时
            //根据接口名分页查询接口搜索
            page = monitorApiService.queryMonitorApiPage(monitorVO);
        }
        List<MonitorApi> monitorApiList = page.getList();
        resultMap.put("monitorApiList", monitorApiList);
        resultMap.put("monitorVO", monitorVO);
        resultMap.put("page", page);
        return resultMap;
    }
    
    
    /**
     * 查看接口失败率版本、运营商、网络、省份分布
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("actionPie")
    @ResponseBody
    public Map<String,Object> actionPie(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        //根据请求方式的showName获得其value
        monitorVO.setMethod(CommonStringType.getMethodValueByShowName(monitorVO.getMethod()));
        //根据异常类型的showName获得其value
        monitorVO.setFailuerType(CommonStringType.getExceptionValueByShowName(monitorVO.getFailuerType()));
        if(monitorVO.getFailuerType().equals(CommonStringType.INTERFACE_EXCEPTION.getValue())){
            //根据接口异常的showName获得其value
            monitorVO.setFailureCode(CommonStringType.getInterfaceExceptionValueByShowName(monitorVO.getFailureCode()));
        }
        
        String[] split = monitorVO.getChooseTimeTableVO().split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDateTable = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
        Date endDateTable = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
        monitorVO.setStartDateTable(startDateTable);
        monitorVO.setEndDateTable(endDateTable);
        
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        //单个接口失败率
        List<MonitorApiFailure> list = monitorFailureApiService.querySingleMonitorFailureApiList(monitorVO);
        List<MonitorApi> amountSumList = monitorApiService.queryAmountSum(monitorVO);
        Double[] proportion = new Double[size];
        DecimalFormat df = new DecimalFormat("#0.00000");
        for(int i=0;i<size;i++){
            for(MonitorApiFailure monitorApiFailure : list){
                Date operDate = monitorApiFailure.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                for(MonitorApi monitorApi : amountSumList){
                    Date monitorApiOperDate = monitorApi.getOperDate();
                    String monitorApiOperDateStr = DateUtil.dateFormat(monitorApiOperDate, "yyyy-MM-dd");
                    if(dateInterval[i].equals(operDateStr) && dateInterval[i].equals(monitorApiOperDateStr)){
                        Long amount = monitorApiFailure.getAmount();
                        Long amountSum = monitorApi.getAmount();
                        String str1 = df.format(((double)amount/amountSum)*100);
                        Double newData1 = Double.parseDouble(str1);
                        proportion[i] = newData1;
                    }
                }
            }
        }
        JSONArray singleMonitorFailuerAPIJsonProportion = doubleArrayToJSONArray(proportion,null);
        resultMap.put("dateInterval", dateInterval);
        resultMap.put("proportion", singleMonitorFailuerAPIJsonProportion);
        
        
        //DecimalFormat df = new DecimalFormat("#0.00");
        //接口失败率版本分布
        List<MonitorApiFailure> monitorFailureApiVersionList = monitorFailureApiService.queryMonitorFailureApiVersionList(monitorVO);
        String[] monitorApiVersions = new String[monitorFailureApiVersionList.size()];
        List<Map<String, Object>> versionsSeriesList = new ArrayList<Map<String, Object>>();
        for(int i=0;i<monitorFailureApiVersionList.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            String apiVersion = monitorFailureApiVersionList.get(i).getApiVersion();
            Long amount = monitorFailureApiVersionList.get(i).getAmount();
            monitorApiVersions[i] = apiVersion;
            map.put("name", apiVersion);
            map.put("value", amount);
            versionsSeriesList.add(map);
        }
        resultMap.put("versionsLegend", monitorApiVersions);
        resultMap.put("versionsSeries", versionsSeriesList);
        
        //接口失败率运营商分布
        List<MonitorApiFailure> monitorFailureApiOperatorsList = monitorFailureApiService.queryMonitorFailureApiOperatorsList(monitorVO);
        String[] monitorApiOperators = new String[monitorFailureApiOperatorsList.size()];
        List<Map<String, Object>> operatorsSeriesList = new ArrayList<Map<String, Object>>();
        for(int i=0;i<monitorFailureApiOperatorsList.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            //根据异常类型的value获得其名称
            String operators = CommonStringType.getOperatorsShowNameByValue(monitorFailureApiOperatorsList.get(i).getOperators());
            Long amount = monitorFailureApiOperatorsList.get(i).getAmount();
            monitorApiOperators[i] = operators;
            map.put("name", operators);
            map.put("value", amount);
            operatorsSeriesList.add(map);
        }
        resultMap.put("operatorsLegend", monitorApiOperators);
        resultMap.put("operatorsSeries", operatorsSeriesList);
        
      //接口失败率网络分布
        List<MonitorApiFailure> monitorFailureApiNetworkTypeList = monitorFailureApiService.queryMonitorFailureApiNetworkTypeList(monitorVO);
        String[] monitorApiNetworkType = new String[monitorFailureApiNetworkTypeList.size()];
        List<Map<String, Object>> networkTypeSeriesList = new ArrayList<Map<String, Object>>();
        for(int i=0;i<monitorFailureApiNetworkTypeList.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            //根据异常类型的value获得其名称
            String networkType = CommonStringType.getNetworkTypeShowNameByValue(monitorFailureApiNetworkTypeList.get(i).getNetworkType());
            Long amount = monitorFailureApiNetworkTypeList.get(i).getAmount();
            monitorApiNetworkType[i] = networkType;
            map.put("name", networkType);
            map.put("value", amount);
            networkTypeSeriesList.add(map);
        }
        resultMap.put("networkTypeLegend", monitorApiNetworkType);
        resultMap.put("networkTypeSeries", networkTypeSeriesList);
        
      //接口失败率省份分布
        List<MonitorApiFailure> monitorFailureApiProvinceList = monitorFailureApiService.queryMonitorFailureApiProvinceList(monitorVO);
        int count = monitorFailureApiProvinceList.size();
        String[] monitorApiProvince = null;
        if(count > 10){
            monitorApiProvince = new String[11];
        }else{
            monitorApiProvince = new String[count];
        }
        List<Map<String, Object>> provinceSeriesList = new ArrayList<Map<String, Object>>();
        Long other = 0l;
        for(int i=0;i<count;i++){
            Map<String, Object> map = new HashMap<String, Object>();
            String province = monitorFailureApiProvinceList.get(i).getProvince();
            Long amount = monitorFailureApiProvinceList.get(i).getAmount();
            if(i < 10){
                monitorApiProvince[i] = province;
                map.put("name", province);
                map.put("value", amount);
                provinceSeriesList.add(map);
            }else{
                other +=  amount; 
            }
        }
        Map<String, Object> mapOther = new HashMap<String, Object>();
        if( count> 10){
            monitorApiProvince[10] = "其他";
            mapOther.put("name", "其他");
            mapOther.put("value", other);
            provinceSeriesList.add(mapOther);
        }
        resultMap.put("provinceLegend", monitorApiProvince);
        resultMap.put("provinceSeries", provinceSeriesList);
        
        return resultMap;
    }
    
    
    /**
     * 查看单个接口不同版本和不同运营商调用耗时
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("actionLine")
    @ResponseBody
    public Map<String,Object> actionLine(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        monitorVO = queryMonitorVO(monitorVO);//获取页面上的查询条件
        //单个接口不同版本和运营商调用耗时X轴数据
        JSONArray monitorAPIJsonXAxis = new JSONArray();
        String[] dateInterval = monitorVO.getDateInterval();
        int size = dateInterval.length;
        for(String str : dateInterval){
            monitorAPIJsonXAxis.add(str);
        }
        
        ////单个接口不同版本调用耗时
        String[] monitorApiVersions = monitorApiService.queryMonitorApiVersion(monitorVO);
        //单个接口不同版本调用耗时
        List<MonitorApi> monitorApiVersionList = monitorApiService.queryMonitorApiVersionList(monitorVO);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for(int j=0;j< monitorApiVersions.length;j++){
            Map<String, Object> map = new HashMap<String, Object>();
            Double[] arr = new Double[size];
            /*for (int i = 0; i < size; i++) {
                arr[i] = 0.0;
            }*/
            for(int i=0;i<size;i++){
                for(MonitorApi monitorApi : monitorApiVersionList){
                    Date operDate = monitorApi.getOperDate();
                    String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                    String apiVersion = monitorApi.getApiVersion();
                    Double avgApiTime = monitorApi.getAvgApiTime();
                    if(dateInterval[i].equals(operDateStr) && monitorApiVersions[j].equals(apiVersion)){
                        arr[i]=avgApiTime;
                    }
                }
            }
            map.put("name", monitorApiVersions[j]);
            map.put("type", "line");
            map.put("data", arr);
            list.add(map);
        }
        resultMap.put("legend", monitorApiVersions);
        resultMap.put("series", list);
        resultMap.put("dateInterval", dateInterval);
        
        //单个接口运营商调用耗时
        List<MonitorApi> monitorApiOperatorsList = monitorApiService.queryMonitorApiOperatorsList(monitorVO);
        //单个接口运营商调用耗时Y轴数据
        Double[] cuData = new Double[size];
        Double[] ctData = new Double[size];
        Double[] cmData = new Double[size];
        Double[] noneData = new Double[size];
        /*for(int i = 0; i < size; i++){
            cuData[i] = 0.0;
            ctData[i] = 0.0;
            cmData[i] = 0.0;
            noneData[i] = 0.0;
        }*/
        for(int i=0;i<size;i++){
            for(MonitorApi monitorApi : monitorApiOperatorsList){
                Date operDate = monitorApi.getOperDate();
                String operDateStr = DateUtil.dateFormat(operDate, "yyyy-MM-dd");
                String operators = monitorApi.getOperators();
                Double avgApiTime = monitorApi.getAvgApiTime();
                if(operDate != null && operators != null){
                    if(operators.equals(CommonStringType.CM.getValue()) && dateInterval[i].equals(operDateStr)){
                        cmData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.CU.getValue()) && dateInterval[i].equals(operDateStr)){
                        cuData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.CT.getValue()) && dateInterval[i].equals(operDateStr)){
                        ctData[i] = avgApiTime;
                    }else if(operators.equals(CommonStringType.NONE1.getValue()) && dateInterval[i].equals(operDateStr)){
                        noneData[i] = avgApiTime;
                    }
                }
            }
        }
        resultMap.put("cuData", cuData);
        resultMap.put("ctData", ctData);
        resultMap.put("cmData", cmData);
        resultMap.put("noneData", noneData);
        return resultMap;
    }
    
    
    /**
     * 接口占比趋势点击事件
     * @param monitorVO
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("ajaxFailureTable")
    @ResponseBody
    public Map<String,Object> ajaxFailureTable(MonitorVO monitorVO,HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String chooseTimeTable = monitorVO.getChooseTimeTableVO();
        String chooseTimeTableVO = DateUtil.formatString(chooseTimeTable, "yyyy-MM-dd", "MM/dd/yyyy");
        monitorVO.setChooseTimeTableVO(chooseTimeTableVO+" - "+chooseTimeTableVO);
        Date startDateTable = DateUtil.parseDate(chooseTimeTable + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDateTable = DateUtil.parseDate(chooseTimeTable + " 23:59:59", "yyyy-MM-dd HH:mm:ss");;
        monitorVO.setStartDateTable(startDateTable);
        monitorVO.setEndDateTable(endDateTable);
        String seriesIndex = monitorVO.getSeriesIndex();
        if(seriesIndex.equals("0")){
            monitorVO.setFailuerType("1");//接口异常
        }else if(seriesIndex.equals("1")){
            monitorVO.setFailuerType("2");//HTTP异常
        }
        //单个接口不同版本调用耗时
        PageInfo<MonitorApiFailure> page = monitorFailureApiService.queryMonitorFailureApiPage(monitorVO);
        List<MonitorApiFailure> list = page.getList();
        for(MonitorApiFailure monitorApiFailure : list){
            String method = monitorApiFailure.getMethod();
            String failuerType = monitorApiFailure.getFailuerType();
            String failureCode = monitorApiFailure.getFailureCode();
            //根据请求方式的value获得其名称
            monitorApiFailure.setMethod(CommonStringType.getMethodShowNameByValue(method));
            //根据异常类型的value获得其名称
            monitorApiFailure.setFailuerType(CommonStringType.getExceptionShowNameByValue(failuerType));
            if("1".equals(failuerType)){
              //根据接口异常的value获得其名称
                monitorApiFailure.setFailureCode(CommonStringType.getInterfaceExceptionShowNameByValue(failureCode));
            }
        }
        resultMap.put("monitorFailureApiList", list);
        resultMap.put("monitorVO", monitorVO);
        resultMap.put("page", page);
        return resultMap;
    }
    
    /**
     * 获取页面上的查询条件
     * @param pageMonitorVO
     * @return
     */
    
	public MonitorVO queryPageMonitorVO(MonitorVO monitorVO){
        //若获取选择时段为null，默认昨日
        if(monitorVO.getChooseTimeVO() == null){
            /*Date date0=new Date();
            SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
            Calendar calendar1 = new GregorianCalendar();
            calendar1.setTime(date0);
            calendar1.add(calendar1.DATE,-0);//把日期往后增加一天.整数往后推,负数往前移动
            Date date1=calendar1.getTime();
            String dateStr1 = formatter1.format(date1);
            monitorVO.setChooseTimeVO(dateStr1 + " - " + dateStr1); */
            Date date = new Date();
            String startDateStr = DateUtil.getStrDayOfMonth(date, -7, "MM/dd/yyyy");
            String endDateStr = DateUtil.getStrDayOfMonth(date, -1, "MM/dd/yyyy");
            monitorVO.setChooseTimeVO(startDateStr + " - " + endDateStr);
        }
        //切割字符串，获取开启时间和结束时间
        String[] split = monitorVO.getChooseTimeVO().split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
        Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
        monitorVO.setStartDate(startDate);
        monitorVO.setEndDate(endDate);
        
        return monitorVO;
    }
    
   
    /**
     * 计算两个日期之间相差的天数 
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(Date sdate,Date bdate) throws ParseException    
    {    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        sdate=sdf.parse(sdf.format(sdate));  
        bdate=sdf.parse(sdf.format(bdate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(bdate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));           
    }   
    
}
